package com.shopping_back.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.file.Path;
import java.nio.file.Paths;

@Configuration
public class StaticResourceConfig implements WebMvcConfigurer {

    @Value("${app.upload.base-dir:uploads}")
    private String uploadBaseDir;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 获取项目根目录下的上传文件夹路径
        Path projectRoot = Paths.get("").toAbsolutePath();
        Path uploadPath = projectRoot.resolve(uploadBaseDir).toAbsolutePath();

        String resourcePath = uploadPath.toString();

        // 确保路径格式正确
        if (!resourcePath.endsWith("/") && !resourcePath.endsWith("\\")) {
            resourcePath += "/";
        }

        // 配置静态资源映射
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:" + resourcePath)
                .setCachePeriod(3600) // 设置缓存时间1小时
                .resourceChain(true); // 启用资源链

        System.out.println("静态资源映射配置:");
        System.out.println("URL路径: /uploads/**");
        System.out.println("文件路径: " + resourcePath);
    }
}